/**
 * @FileName: RemunerationController.java
 * @Author
 * @Description:
 * @Date 2016年1月11日 下午1:56:23
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.math.BigDecimal;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.bean.OrgNode;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.ClerkReward;
import cn.hpclub.server.util.InterfaceUtil;

public class ClerkrewardController extends BaseAdminController<ClerkReward>{
    private static final String MESSAGE                = "message";
    private static final String STATUS                 = "status";
    private static final String MODULE_ID              = "moduleid";
    private static final String SINGLE_CAP             = "single_cap";

    private static final String ORG_ID                 = "orgID";
    private static final String KEY_CHARGE             = "charge";                                     // 缴费订单
    private static final String KEY_NEW_CARD           = "newcard";                                    // 开卡
    private static final String KEY_SELECTED_NETWORK   = "selectedNetwork";                            // 开卡
    private static final String KEY_TARRIF             = "tarrif";                                     // 资费办理
    private static final String KEY_REAL_NAME          = "realname";                                   // 实名补登记
    private static final String KEY_MARKET             = "market";                                     // 营销活动
    private static final String KEY_BROAD_BAND         = "broadband";                                  // 宽带预约
    private static final String KEY_TOTAL              = "total";                                      // 总封顶金额
    // 大掌柜业务模块区分:1缴费订单,2实名开卡,3选号入网,4资费办理,5实名补登记,6营销活动,7宽带预约

    private final static int    CHARGE                 = 1;                                            // 缴费订单
    private final static int    NEW_CARD               = 2;                                            // 实名开卡
    private final static int    SELECTED_NETWORK       = 3;                                            // 选号入网
    private final static int    TARRIF                 = 4;                                            // 资费办理
    private final static int    REAL_NAME_REGISTRATION = 5;                                            // 实名补登记
    private final static int    MAKRET_CAMPAIGN        = 6;                                            // 营销活动
    private final static int    BROAD_BAND_RESERVATION = 7;                                            // 宽带预约
    private final static int    TOTAL_MAX              = 100;                                          // 总封顶金额
    private static Logger       log                    = LoggerFactory.getLogger(RoleController.class);

    /**
     * @Title: detail
     * @Description:店员酬金配置详情 void
     */
    public void detail(){
        List<Entry<String, Integer>> list = getCityLevelOrgList();
        int defaultOrgId = 0;
        if(!list.isEmpty()){
            defaultOrgId = list.get(0).getValue();
            List<Record> records = ClerkReward.dao.getClerkReward(defaultOrgId);
            getRewardMap(records);
        }
        setAttr(ORG_ID, defaultOrgId);
        setAttr("orgs", list);
        setAttr("noData", list.isEmpty());
        render("/admin/clerk_reward.tpl");
    }

    /**
     * @Title: getDetail
     * @Description:根据OrgID，获取该机构的配置信息 void
     */
    public void getDetail(){
        Integer orgId = getParaToInt(ORG_ID);
        List<Record> records = ClerkReward.dao.getClerkReward(orgId);
        JSONObject jo = new JSONObject();
        jo.put(STATUS, 200);
        jo.put(MESSAGE, "success");
        if(records == null || records.size() == 0){
            /* 数据库中不存在值，返回默认值，用于更新界面 */
            jo.put(KEY_CHARGE, 0);
            jo.put(KEY_NEW_CARD, 0);
            jo.put(KEY_SELECTED_NETWORK, 0);
            jo.put(KEY_TARRIF, 0);
            jo.put(KEY_REAL_NAME, 0);
            jo.put(KEY_MARKET, 0);
            jo.put(KEY_BROAD_BAND, 0);
            jo.put(KEY_TOTAL, 0);
        } else{
            /* 返回实际数据 */
            for(Record record : records){
                BigDecimal value = record.getBigDecimal(SINGLE_CAP);
                int moduleID = record.getInt(MODULE_ID);
                String key = getKeyByModuleID(moduleID);
                jo.put(key, value);
            }
        }
        renderJson(jo.toString());
    }

    /**
     * @Title: save
     * @Description:保存设置 void
     */
    @Before(Tx.class)
    public void save(){
        log.info("clerkreward.save");
        int orgID = Integer.parseInt(getPara(ORG_ID));
        List<Record> list = ClerkReward.dao.getClerkReward(orgID);
        log.info("clerkreward.list.size=" + list.size());
        if(list.size() > 0 && !ClerkReward.dao.deleteReward(orgID)){
            log.error("delete orgId=" + orgID + " reward failed.");
            return;
        }
        int adminId = InterfaceUtil.getAdminId();
        saveReward(orgID, getMoudleID(KEY_SELECTED_NETWORK), Constant.APPID, getPara(KEY_SELECTED_NETWORK), adminId);
        saveReward(orgID, getMoudleID(KEY_CHARGE), Constant.APPID, getPara(KEY_CHARGE), adminId);
        saveReward(orgID, getMoudleID(KEY_TARRIF), Constant.APPID, getPara(KEY_TARRIF), adminId);
        saveReward(orgID, getMoudleID(KEY_NEW_CARD), Constant.APPID, getPara(KEY_NEW_CARD), adminId);
        saveReward(orgID, getMoudleID(KEY_REAL_NAME), Constant.APPID, getPara(KEY_REAL_NAME), adminId);
        saveReward(orgID, getMoudleID(KEY_MARKET), Constant.APPID, getPara(KEY_MARKET), adminId);
        saveReward(orgID, getMoudleID(KEY_BROAD_BAND), Constant.APPID, getPara(KEY_BROAD_BAND), adminId);
        saveReward(orgID, getMoudleID(KEY_TOTAL), Constant.APPID, getPara(KEY_TOTAL), adminId);
        renderJson(new JSONObject().put(STATUS, 200).put(MESSAGE, "保存成功！").toString());
    }

    /**
     * @Title: saveReward
     * @Description:保存酬金配置记录到数据库
     * @param orgID
     *            机构ID
     * @param moduleID
     *            酬金类型
     * @param appID
     *            应用ID
     * @param singleCap
     *            酬金上限值
     * @param creator
     *            创建者ID void
     */
    private void saveReward(int orgID, int moduleID, int appID, String singleCap, int creator){
        log.info("orgID=" + orgID + ",moduleID=" + moduleID + ",appID=" + appID + ",singleCap=" + singleCap
                + ",creator=" + creator);
        if(StrKit.isBlank(singleCap)){
            singleCap = "0";
        }
        BigDecimal singCapValue = new BigDecimal(singleCap);
        ClerkReward clerkReward = getModel(ClerkReward.class);
        clerkReward.set("appid", appID);
        clerkReward.set("orgid", orgID);
        clerkReward.set(MODULE_ID, moduleID);
        clerkReward.set(SINGLE_CAP, singCapValue);
        clerkReward.set("creator", creator);
        clerkReward.set("enable", 1);
        clerkReward.set("addTime", new Date());
        clerkReward.save();
    }

    /**
     * @Title: getOrgMaps
     * @Description:获取市级分公司构集合
     * @return Map<String,Integer>
     */
    private List<Entry<String, Integer>> getCityLevelOrgList(){
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();

        OrgNode root = InterfaceUtil.getOrgTree(InterfaceUtil.getIdTop(), 1, false);
        if(root == null || root.getSubNode() == null || root.getSubNode().size() == 0){
            return list;
        }
        /* 大掌柜根节点，显示所有地市分公司 */
        int accountOrgId = InterfaceUtil.getOrgId();
        if(accountOrgId == root.getId()){
            for(OrgNode node : root.getSubNode()){
                list.add(new SimpleEntry<String, Integer>(node.getDisplayName(), node.getId()));
            }
        } else{
            for(OrgNode node : root.getSubNode()){
                if(accountOrgId == node.getId()){
                    list.add(new SimpleEntry<String, Integer>(node.getDisplayName(), node.getId()));
                }
            }
        }
        return list;
    }

    /**
     * @Title: getRewardMap
     * @Description:获取酬金数据集合
     * @param records
     *            酬金记录 void
     */
    private void getRewardMap(List<Record> records){
        if(records != null){
            for(Record record : records){
                BigDecimal value = record.getBigDecimal(SINGLE_CAP);
                int moduleID = record.getInt(MODULE_ID);
                String key = getKeyByModuleID(moduleID);
                if(!StrKit.isBlank(key)){
                    setAttr(key, value);
                }
            }
        }
    }

    /**
     * @Title: getMoudleID
     * @Description:根据酬金字段名获取对应moduleID
     * @param moduleName
     *            酬金字段名
     * @return int moduleID
     */
    private int getMoudleID(String moduleName){
        if(moduleName.equals(KEY_CHARGE)){
            return CHARGE;
        } else if(moduleName.equals(KEY_TARRIF)){
            return TARRIF;
        } else if(moduleName.equals(KEY_NEW_CARD)){
            return NEW_CARD;
        } else if(moduleName.equals(KEY_REAL_NAME)){
            return REAL_NAME_REGISTRATION;
        } else if(moduleName.equals(KEY_MARKET)){
            return MAKRET_CAMPAIGN;
        } else if(moduleName.equals(KEY_BROAD_BAND)){
            return BROAD_BAND_RESERVATION;
        } else if(moduleName.equals(KEY_TOTAL)){
            return TOTAL_MAX;
        } else if(moduleName.equals(KEY_SELECTED_NETWORK)){
            return SELECTED_NETWORK;
        } else{
            throw new IllegalArgumentException(moduleName + " is not match moduleID.");
        }
    }

    /**
     * @Title: getKeyByModuleID
     * @Description:根据酬金moduleID获取酬金字段名
     * @param moduleID
     * @return String 酬金字段名
     */
    private String getKeyByModuleID(int moduleID){
        switch(moduleID){
            case SELECTED_NETWORK:
                return KEY_SELECTED_NETWORK;
            case CHARGE:
                return KEY_CHARGE;
            case TARRIF:
                return KEY_TARRIF;
            case NEW_CARD:
                return KEY_NEW_CARD;
            case REAL_NAME_REGISTRATION:
                return KEY_REAL_NAME;
            case MAKRET_CAMPAIGN:
                return KEY_MARKET;
            case BROAD_BAND_RESERVATION:
                return KEY_BROAD_BAND;
            case TOTAL_MAX:
                return KEY_TOTAL;
            default:
                return "";
        }
    }
}
